package cn.micro.keep.accounts.auth;


import cn.micro.keep.accounts.common.enums.LoginTypeEnum;
import cn.micro.keep.accounts.common.utils.SecurityUtil;
import cn.micro.keep.accounts.entity.AccountDimUser;
import cn.micro.keep.accounts.exception.MicroSysException;
import cn.micro.keep.accounts.service.AccountDimUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Component
@Slf4j
@RequiredArgsConstructor
public class MyAuthenticationProvider implements AuthenticationProvider {

    private final AccountDimUserService accountDimUserService;


    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = String.valueOf(authentication.getName());
        String password = String.valueOf(authentication.getCredentials());
        return authenticate(username, password,null);
    }

    public Authentication authenticate(String username, String password,Integer loginType) {
        //获取用户基本信息
        AccountDimUser accountDimUser = accountDimUserService.getByUsernameOrPhoneOrOpenId(username);
        if (Objects.equals(loginType, LoginTypeEnum.USERNAME_PASSWORD.getValue()) /*密码模式*/){
            if (accountDimUser == null){
                throw new MicroSysException("账号不存在！");
            }
            if (accountDimUser.getPassword() == null || !SecurityUtil.matchesPassword(password,accountDimUser.getPassword())){
                throw new MicroSysException("密码错误！");
            }
        } else if (Objects.equals(loginType,LoginTypeEnum.WECHAT_MOBILE.getValue()) /*手机验证码模式*/){
            if (accountDimUser == null){
                //验证码验证码是否正确

            }
        } else if (Objects.equals(loginType,LoginTypeEnum.WECHAT_OPENID.getValue()) /*微信授权模式*/) {
            //使用code换取openid

        }else {
            throw new RuntimeException("未知的登录模式");
        }
        LoginUserDetail loginUserDetail = new  LoginUserDetail(accountDimUser.getId(),accountDimUser.getUsername(),accountDimUser.getStatus());
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(loginUserDetail, null, null);
        return usernamePasswordAuthenticationToken;
    }


    public LoginUserDetail getLoginUserDetail(String username) {
        return null;
    }




    @Override
    public boolean supports(Class<?> aClass) {
        return aClass.equals(UsernamePasswordAuthenticationToken.class);
    }
}
